package com.alan.weather.common.responseResult.exception;

import com.alan.weather.common.responseResult.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> ex01(SQLIntegrityConstraintViolationException e){
        String message = e.getMessage();
        String msg= "";
        if (message.contains("Duplicate")){
            String[] strings = message.split(" ");
            msg = "用户名 "+strings[2]+" 已存在！";
            return R.error(msg);
        }
        return R.error("未知错误");
    }


}
